Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
Trying to draw a canvas with two "players" but after adding more code it doesn't work?

I'm trying to draw a canvas with two blocks in it, which I'm going to turn into two players/characters. However after the first few lines of code, if I add anything else to it then nothing loads anymore. I am just starting to learn JavaScript so I have no clue why it isn't working.

var canvas = document.getElementById('canvas');
var c = canvas.getContext("2d");



canvas.width = 1000 
canvas.height = 500 

c.fillRect(50, 50, canvas.width, canvas.height)


// If i try add the code below then everything disappears. 
/*
 class Sprite {
    constructor(position) {
this.position = position

    }

    draw() {
     c.fillStyle='red'
     c.fillRect(this.position.x, this.position.y, 50, 150)

    }
}

const player = new Sprite( {
        x: 0,
        y: 0
    } )

player.draw()

const enemy = new Sprite(
    {
        x: 400,
        y: 100
    }
)

enemy.draw()

console.log(player) */
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>STREET FIGHTER</title>
 </head>

<body>
 
  <canvas id="canvas"></canvas>
  <script src="index.js"></script>

</body>

</html>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Works fine for me...
I see nothing that will cause the behavior you describe
See code below, I removed the comment on your class:

var canvas = document.getElementById('canvas');
var c = canvas.getContext("2d");
canvas.width = canvas.height = 140

c.fillRect(50, 30, canvas.width, canvas.height)


class Sprite {
  constructor(rect, color) {
    this.rect = rect
    this.color = color
  }

  draw() {
    c.fillStyle = this.color
    c.fillRect(this.rect.x, this.rect.y, this.rect.w, this.rect.h)
  }
}

const player = new Sprite({ x: 15, y: 10, w:9, h:9 }, "red")
player.draw()

const enemy = new Sprite({ x: 90, y: 35, w:20, h:10}, "cyan")
enemy.draw()

console.log(player)
<canvas id="canvas"></canvas>

I change a bit the parameters in the constructor but nothing that will affect your original code

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda